package vendingMachine.inventory;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

public class InventoryDatabase implements IInventoryDatabase
{

  public ArrayList<Item> createItemList()
  {
    ArrayList<Item> items = new ArrayList<Item>();

    // Open the file for reading
    try
    {
      BufferedReader br = new BufferedReader(
          new FileReader("InventoryData.txt"));

      String line = null;

      line = br.readLine();
      if (line == null)
        return null;

      while ((line = br.readLine()) != null)
      {
        String[] result = line.split(",");

        Item item = new Item();
        item.ID = new Integer(result[0]);
        item.quantity = new Integer(result[1]);
        item.price = new Double(result[2]);
        item.row = new Integer(result[3]);
        item.column = new Integer(result[4]);
        item.description = result[5];

        items.add(item);

      }

      if (items.size() > 0)
        return items;
      else
        return null;
    }
    catch (IOException e)
    {
      System.err.println("Error: " + e);
    }

    return null;

  }

  public boolean reduceQuantity(int itemID, int quantity) throws IOException
  {
    // Create a copy the database
    ArrayList<Item> items = createItemList();

    Iterator<Item> itemsIt = items.iterator();

    // Update the item
    while (itemsIt.hasNext())
    {
      Item item = itemsIt.next();

      if (item.ID == itemID)
      {
        item.quantity -= quantity;
        break;
      }
    }

    storeItemList(items);

    return false;
  }

  private void storeItemList(ArrayList<Item> items) throws IOException
  {
    BufferedWriter bw = new BufferedWriter(new FileWriter("InventoryData.txt"));

    bw.write("ID,Quantity,Price,Row,Column,Description");
    bw.newLine();

    Iterator<Item> itemsIt = items.iterator();

    // Update the item
    while (itemsIt.hasNext())
    {
      Item item = itemsIt.next();

      bw.write(new Integer(item.ID).toString() + ","
          + new Integer(item.quantity).toString() + ","
          + new Double(item.price).toString() + ","
          + new Integer(item.row).toString() + ","
          + new Integer(item.column).toString() + "," + item.description);
      bw.newLine();

    }

    bw.close();
  }

  public Item getItem(int theID)
  {
    // TODO Auto-generated method stub
    Iterator<Item> itemsIt = createItemList().iterator();

    // Update the item
    while (itemsIt.hasNext())
    {
      Item item = itemsIt.next();
      if(theID == item.getID())
      {
        return item;
      }
    }

    return null;
  }

}
